Scroll Progress Bar

Array Of Strings

In C, an array of strings is a collection of multiple strings, where each string is an array of characters. Each string in the array is terminated by a null character ('\0'), which marks the end of the string. An array of strings can be visualized as a two-dimensional array, where each row represents a string.

Usage and Syntax:

To declare an array of strings in C, you need to declare a two-dimensional character array (a 2D array of characters), where each row represents a string. The size of the array should be specified based on the maximum length of the strings it will hold.

char array_name[num_of_strings][max_string_length + 1];

The +1 in the size accounts for the null character at the end of each string.

Sample Code with Explanation and Output:

#include <stdio.h>
#include <string.h>

int main() {
    // Declaration and initialization of an array of strings
    char names[3][20] = {
        "Alice",
        "Bob",
        "Charlie"
    };

    // Printing the array of strings
    printf("Array of Strings:\n");
    for (int i = 0; i < 3; i++) {
        printf("%s\n", names[i]);
    }

    // Accessing individual characters in a string
    printf("First character of the second string: %c\n", names[1][0]); // 'B'

    // Modifying a string
    strcpy(names[2], "David");

    // Printing the modified array of strings
    printf("Modified Array of Strings:\n");
    for (int i = 0; i < 3; i++) {
        printf("%s\n", names[i]);
    }

    return 0;
}
Output:


Array of Strings:
Alice
Bob
Charlie
First character of the second string: B
Modified Array of Strings:
Alice
Bob
David
Explanation:
  • In the sample code, declare an array of strings names that can hold three strings of up to 19 characters each (plus 1 for the null terminator).
  • Initialize the array of strings with three names: "Alice", "Bob", and "Charlie".
  • Then use a loop to print each string in the array.
  • Next, access and print the first character of the second string (index 1), which is 'B'.
  • After that, modify the third string by using strcpy to copy "David" into the third row of the array (index 2).
  • Finally, print the modified array of strings to see the updated content.
  • Note: When working with arrays of strings, ensure that the strings do not exceed the allocated buffer size to avoid buffer overflows and undefined behaviour.

What is an array of strings in C?


Collection

How do you declare an array of strings in C?


Declaration

How do you initialize an array of strings in C?


Initialization

How can you access individual characters in an array of strings in C?


Indexing

What is the significance of the null character in C strings?


Termination